package com.dufang.Thread07Lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName:ThreadLock
 * @Description Lock是一个接口
 *       实现类：ReentrantLock
 *         方法：lock()获取锁
 *              unlock()释放锁
 * @Author Administrator
 * @Date 2025/7/7/007 20:12
 * @Version 1.0
 **/
public class ThreadLock implements Runnable{
     int ticket=100;

     //创建Lock对象
    Lock lock=new ReentrantLock();
    @Override
    public void run() {
        while(true) {
            try{
                Thread.sleep(100L);

                //获取锁
                lock.lock();
                if (ticket > 0) {
                    System.out.println(Thread.currentThread().getName() + "买了第" + ticket + "票");
                    ticket--;
                }
            }catch (InterruptedException e){
                throw new RuntimeException(e);
            }finally {
                //释放锁  放在finally里保证锁一定释放
                lock.lock();
            }
        }
    }
}
